package com.yuanjin.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

public class HttpUploadsave{


	public static String sendHttpClientPost(String path,
			Map<String, String> map, String encode) {
		//创建�?��名�?值对目录
		ArrayList<NameValuePair> list=new ArrayList<NameValuePair>();
		if (map!=null&&!map.isEmpty()) {
			for(Map.Entry<String, String>entry:map.entrySet()){
				//将map中的数据传到list�?
				list.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
			}
		}
		try {
			//实现将请求的参数封装到表单中，Form-表格
			UrlEncodedFormEntity entity=new UrlEncodedFormEntity(list, encode);
			//使用Post方式提交数据
			HttpPost httpPost=new HttpPost(path);
//			
			httpPost.setEntity(entity);
			//执行Post请求
			DefaultHttpClient client=new DefaultHttpClient();
			//client.excute()为执行服务，httpResponse为执行后的返回�?
			HttpResponse httpResponse=client.execute(httpPost);
			//判断返回�?
			if (httpResponse.getStatusLine().getStatusCode()==200) {
				//返回的是�?��输出�?
				return changeInputStream(httpResponse.getEntity().getContent(),encode);
			}
			
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "";
	}

	/**
	 * 将一个输入流转换成指定编码的字符�?
	 * 
	 * @param inputStream
	 * @param encode
	 * @return
	 */
	public static String changeInputStream(InputStream inputStream,
			String encode) {
		// �?��称为内存流，写在内存当中。可以获取内存缓冲区的数据转化为数组
		ByteArrayOutputStream outputstream = new ByteArrayOutputStream();
		byte[] data = new byte[1024];
		int len = 0;// 从输入流中读到数据的数目
		String result = "";
		if (inputStream != null) {
			try {
				while ((len = inputStream.read(data)) != -1) {// 获取数据并存到data字节数组�?
					outputstream.write(data, 0, len);
				}
				// 将输出流的字节数组数组以encode编码 转化为string
				result = new String(outputstream.toByteArray(), encode);
				// result=new String(data, encode);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return result;
	}
}
